import {Component, OnInit} from '@angular/core';
import {ReportService} from '../report.service';
import {FormBuilder,  FormGroup, Validators} from '@angular/forms';
import {ConfirmationService} from 'primeng/primeng';
import {ActivatedRoute, Router} from '@angular/router';
import {environment} from '../../../environments/environment';
import {MessageService} from 'primeng/components/common/messageservice';
import {BasePage} from '../../base.page';
const PHOTOURL = environment.url.management + '/fault/fault_imgs_upload';
@Component({
  selector: 'app-report-start',
  templateUrl: './report-start.component.html',
  styleUrls: ['./report-start.component.scss']
})
export class ReportStartComponent extends BasePage implements OnInit {
  initStartTime: Date;
  msgs = [];
  submitReportData;
  reportForm: FormGroup; //报障表单验证声明
  fb: FormBuilder =  new FormBuilder();
  submitted: boolean;
  reportStatus;
  displayPersonel: boolean = false;
  brand: string;
  brandoptions;
  uploadPhotoUrl = PHOTOURL;
  files =[];
  showreportAddEquement: boolean = false;
  displayLocation: boolean = false;
  dataSource = [];
  viewState;
  state;
  title;
  reportData = {};
  editDataSource = [];
  editInspections = [];
  totalRecords;

  qureyModel = {
    field: '',
    value: ''
  };
  constructor( private reportService: ReportService,
               private router: Router,
               private route: ActivatedRoute,
               public confirmationService: ConfirmationService,
               public messageService: MessageService
  ) {
    super(confirmationService, messageService);
  }
  ngOnInit() {
    this.files =[1,2]
    this.title = '保障发起'
    this.initStartTime = new Date();
    this.viewState = 'apply'
    //初始化验证
    this.reportStatus = ['未处理', '已处理'];
    this.submitReportData = {
      'people': this.brand,
      'fault_type': '',
      'status': '',
      'time': this.reportService.getFormatTime(),
      'location': '',
      'content': '',
      'img_url': '',
      'title': '',
      'submitdevices': ''
    };
    this.reportForm = this.fb.group({
      'cid': [''],
      'fault_type': ['', Validators.required],
      'time': ['', Validators.required],
      'people': ['', Validators.required],
      'location': [''],
      'title': ['', Validators.required],
      'content': ['', Validators.required],
      'asset': [''],
    });
    this.route.queryParams.subscribe(params=>{
      if(params['cid']&&params['state'] && params['title']){
        this.title = params['title']
        this.viewState = params['state'];
        let queryModel  ={
          'cid':params['cid'] ,
          'people': "",
          'fault_type': "",
          'status': "",
          'time_start': "",
          'time_end': "",
        }
        this.reportService.getHistoryReport(queryModel).subscribe(data=>{
          this.reportData = data[0];
          console.log(this.reportData);
          this.reportData['devices']?this.reportData['devices']:this.reportData['devices']=[];
          let devices = [];
          for (let i = 0; i < this.reportData['devices'].length; i++){
            let temp = this.reportData['devices'][i];
            devices.push(temp['ano']);
          }
          this.editDataSource = this.reportData['devices']?this.reportData['devices']:[];
          if(!this.editDataSource){
            this.editDataSource = [];
            this.editInspections =[];
            this.totalRecords = 0;
          }
          this.submitReportData.submitdevices = this.reportData['devices'];
          this.reportData['devices'] = devices.join(';');
        })
      }
    })
  }

  onSubmitReport(){
    this.reportService.onSubmitReport(this.submitReportData).subscribe(() => {
      this.router.navigate(['../history'], {relativeTo: this.route});
    });
  }
//修改提交
  updateReportSubmit(submitData,reportData){
    submitData['subdevices'] = reportData;
    submitData['status'] = this.reportStatus[0];
    this.reportService.updateReport(submitData).subscribe(()=>{
      this.router.navigate(['../history'],{queryParams:{title:'历史保障'},relativeTo:this.route})
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err;
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };

  //图片上传
  onBasicUploadAuto(event) {

    let res = JSON.parse(event.xhr.responseText);
    if (res['errcode'] !== '00000'){
      this.toast(res['errmsg']);
      // this.msgs.push({severity: 'error', summary: '提示消息', detail: res['errmsg']});
      // this.message.push({severity: 'info', summary: 'File Uploaded', detail: res['errmsg']});
      // this.msgs = [];
      return;
    }
    let photoUrl = res['datas'];
    let imgurl = [];
    for (let i = 0; i < photoUrl.length; i++){
      imgurl.push(photoUrl[i].path);
    }
    this.submitReportData.img_url = imgurl.join(';');
  }
  searchSuggest(searchText, name){
    this.qureyModel = {
      field: name,
      value: searchText.query
    };
    for (let key in this.qureyModel){
      this.qureyModel[key] = this.qureyModel[key].trim();
    }
    this.reportService.searchChange(this.qureyModel).subscribe(
      datas => {
        switch (name){
          case 'fault_type':
            this.brandoptions = datas;
            console.log(this.brandoptions)
            break;
        }
      }
    );
  }
  displayEmitter(event) {
    this.displayPersonel = event;
  }
  dataEmitter(event) {
    if(this.viewState === 'apply'){
      this.submitReportData.people  = event.name;
    }else{
      this.reportData['people'] = event.name;
    }
  }
  showPersonMask(){
    this.displayPersonel = !this.displayPersonel;
  }
  clearpeopleDialog () {
    this.submitReportData.people = '';
    this.reportData['people'] = '';
  }
  clearLocationDialog () {
    this.submitReportData.location = '';
    this.reportData['location'] = '';
  }

  clearAssetDialog () {
    this.submitReportData.devices = '';
    this.reportData['devices'] = '';
  }

  showreportAddEquementMask(){
    this.showreportAddEquement = !this.showreportAddEquement;
  }
  closeAddEquementMask(bool){
    this.showreportAddEquement = bool;
  }


  addDev(metail){
    this.showreportAddEquement = false;
    let devices = [];
    for (let i = 0; i < metail.length; i++){
      let temp = metail[i];
      devices.push(temp['ano']);
    }
    this.submitReportData.submitdevices = metail;
    if(this.viewState === 'apply'){
      this.submitReportData.devices = devices.join(';');
    }else{
      this.reportData['devices'] = metail;
      this.reportData['devices'] = devices.join(';');
    }


  }
  showreportAddLocationMask(){
      this.displayLocation = !this.displayLocation;
  }
  closeAddLocationMask(bool){
    this.displayLocation = bool;
  }
  addConstructionOrg(org){
    this.submitReportData.location = [];
    for (let i = 0; i < org.length; i++){
      this.submitReportData.location.push(org[i]['label']);
    }
    if(this.viewState === 'apply'){
      this.submitReportData.location =  this.submitReportData.location.join('>');
    }else {
      this.reportData['location']= this.submitReportData['location'].join('>') ;
    }
    this.displayLocation = false;
  }
  //保存
  addReportSave(submitData){
    let devices = [];
    submitData.devices = devices;
    this.reportService.queryReportSave(this.submitReportData).subscribe(()=>{
      this.router.navigate(['../history'],{queryParams:{title:'历史保障'},relativeTo:this.route})
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err;
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };
  //修改保存
  updateReportSave(submitData){
    submitData['subdevices'] = this.submitReportData.submitdevices;
    this.reportService.updateReport(submitData).subscribe(()=>{
      this.router.navigate(['../history'],{queryParams:{title:'历史保障'},relativeTo:this.route})
    },(err:Error)=>{
      let message ;
      if(JSON.parse(JSON.stringify(err)).status===504){
        message = '似乎网络出现了问题，稍后重试'
      }else{
        message =err;
      }
      this.confirmationService.confirm({
        message: message,
        rejectVisible:false,
      })
    })
  };
  formSave(){
    if(this.viewState === 'apply'){
      this.addReportSave(this.submitReportData);
    }else if(this.viewState === 'update'){
      this.updateReportSave(this.reportData);
    }
  }
  formSubmit(){
    if(this.viewState === 'apply'){
      this.onSubmitReport();
    }else if(this.viewState === 'update'){
      this.updateReportSubmit(this.reportData,this.editDataSource);
    }
  }
  goBack() {
    this.router.navigate(['../history'], {relativeTo: this.route});
  }
}

